<template>
  <div class="container">
    <!-- 按钮部分 -->
    <div class="handle-box">
      <el-button-group>
        <el-button type="success" @click="addMember">添加学员</el-button>
        <el-button type="info" @click="batchExport">批量导入学员</el-button>
      </el-button-group>
    </div>

    <el-divider></el-divider>

    <!-- 学员列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="学员姓名" width="120" />
      <el-table-column prop="studentId" label="学号" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.gender === 'M' ? '男' : scope.row.gender === 'F' ? '女' : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="birthday" label="出生日期" width="120" />
      <el-table-column prop="school" label="学校" width="180" />
      <el-table-column prop="grade" label="年级" width="120" />
      <el-table-column prop="contactPhone" label="学员手机号" width="130" />
      <el-table-column prop="parentName" label="家长姓名" width="100" />
      <el-table-column prop="parentPhone" label="家长手机号" width="130" />
      <el-table-column prop="currentLevel" label="当前课程" width="120" />
      <el-table-column prop="enrollmentDate" label="入学日期" width="120" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'info'">
            {{ scope.row.status ? '在读' : '停课' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="180" />

      <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
          <el-row class="btn-opt">
            <el-button type="primary" link size="small" @click="memberEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="cancelMember(scope.row)">注销</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-divider></el-divider>

    <!-- 分页组件 -->
    <el-row>
      <el-col :span="20">
        <el-pagination
          v-model:current-page="pageData.pageCurrent"
          :page-size="pageData.pageSize"
          layout="prev, pager, next"
          :total="pageData.pageTotal"
          background
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>

    <!-- 添加学员 -->
    <el-drawer v-model="drawer" :direction="direction" size="50%">
      <template #header>
        <h2>添加学员</h2>
      </template>
      <div class="div-step">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="学员信息" />
          <el-step title="绑定课时卡" />
          <el-step title="完成" />
        </el-steps>
      </div>
      <div class="div-form">
        <EditAddForm v-if="active == 1" :form="form" v-model:active="active" v-model:drawer="drawer" type="add" />
        <MemberBindForm v-else-if="active == 2" :cardForm="cardForm" v-model:active="active" v-model:drawer="drawer" />
        <div class="div-formFinish" v-else>
          <span style="line-height: 120px;">学员注册完成</span>
        </div>
      </div>
    </el-drawer>

    <!-- 编辑学员 -->
    <el-drawer v-model="editMemberDrawer" direction="rtl" size="50%">
      <template #header>
        <h2>编辑学员</h2>
      </template>
      <div class="div-form">
        <EditAddForm :form="form" type="edit" @saved="saveMemberEdit" @close="editMemberDrawer = false" />
      </div>
    </el-drawer>

    <!-- 批量导入 -->
    <el-drawer v-model="batchExportDrawer" direction="rtl" size="50%">
      <template #header>
        <h2>学员批量导入</h2>
      </template>
      <BatchExportMember />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'

import EditAddForm from './memberComponent/EditAddForm.vue'
import MemberBindForm from './memberComponent/MemberBindForm.vue'
import BatchExportMember from './memberComponent/BatchExportMember.vue'

const pageData = reactive({ pageCurrent: 1, pageSize: 5, pageTotal: 0 })
const tableData = ref([])

const getData = async () => {
  const res = await axios.get('http://localhost:8080/api/students')
  const all = Array.isArray(res.data) ? res.data : res.data.data
  pageData.pageTotal = all.length
  const start = (pageData.pageCurrent - 1) * pageData.pageSize
  const end = pageData.pageCurrent * pageData.pageSize
  tableData.value = all.slice(start, end)
}
getData()

const handleCurrentChange = (val) => {
  pageData.pageCurrent = val
  getData()
}

const form = reactive({
  studentId: '', name: '', gender: 'M', age: null,
  birthday: '', school: '', grade: '', contactPhone: '',
  parentName: '', parentPhone: '', currentLevel: '',
  enrollmentDate: '', status: true, remark: ''
})

const cardForm = reactive({
  cardId: '', validCount: 50, validDay: 30,
  receivedMoney: '', payMode: [], note: ''
})

const addMember = () => {
  drawer.value = true
  active.value = 1
  Object.assign(form, {
    studentId: '', name: '', gender: 'M', age: null,
    birthday: '', school: '', grade: '', contactPhone: '',
    parentName: '', parentPhone: '', currentLevel: '',
    enrollmentDate: '', status: true, remark: ''
  })
  Object.assign(cardForm, {
    cardId: '', validCount: 50, validDay: 30,
    receivedMoney: '', payMode: [], note: ''
  })
}

const direction = ref('rtl')
const drawer = ref(false)
const active = ref(1)

const editMemberDrawer = ref(false)
const memberEdit = (row) => {
  Object.assign(form, row)
  editMemberDrawer.value = true
}

const saveMemberEdit = async () => {
  try {
    await axios.put(`http://localhost:8080/api/students/${form.studentId}`, form)
    ElMessage.success('修改成功')
    editMemberDrawer.value = false
    await getData()
  } catch (err) {
    console.error(err)
    ElMessage.error('修改失败')
  }
}

// 删除详情相关内容

const cancelMember = async (row) => {
  try {
    await ElMessageBox.confirm('确定注销学员吗?', '注销学员', {
      confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
    })
    // 实现注销功能，假设为删除接口
    await axios.delete(`http://localhost:8080/api/students/${row.studentId}`)
    ElMessage.success('注销成功')
    await getData()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('注销失败')
    }
  }
}

const batchExportDrawer = ref(false)
const batchExport = () => {
  batchExportDrawer.value = true
}
</script>

<style scoped lang="less">
.handle-box { margin-bottom: 20px; }
.mr10 { margin-right: 10px; }
.w50 { width: 45%; }
.div-step {
  width: 100%; height: 120px; text-align: center;
}
.div-form {
  text-align: center; width: 90%; margin-left: 20px;
}
.div-formFinish {
  color: #676a6c; background-color: #eee;
  font-size: 45px; height: 120px; text-align: center; padding: 20px auto;
}
.detail-des { margin: 10px 20px; }
.btn-opt {
  font-size: 13px;
  .el-button {
    margin-left: 3px; font-size: 13px; padding: 1px 6px;
  }
}
.mt20 { margin-top: 20px; }
</style>